package com.ansatsing.chat.server;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundMessageHandlerAdapter;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;

public class ChatServerHandler extends ChannelInboundMessageHandlerAdapter<String> {
    private static ChannelGroup channels = new DefaultChannelGroup();

    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        Channel incoming = ctx.channel();
        for(Channel channel:channels){
            channel.write("[Server] - "+incoming.remoteAddress()+" has joined!\n");
        }
        channels.add(ctx.channel());
    }

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        Channel incoming = ctx.channel();
        for(Channel channel:channels){
            if(incoming == channel) continue;
            channel.write("[Server] - "+incoming.remoteAddress()+" has left!\n");
        }
        channels.remove(ctx.channel());
    }

    public void messageReceived(ChannelHandlerContext channelHandlerContext, String s) throws Exception {
        Channel incoming = channelHandlerContext.channel();
        String message = new String(s.getBytes(),"UTF-8");
        for(Channel channel:channels){
            if(channel == incoming) continue;
            channel.write("["+incoming.remoteAddress()+"] "+message+"\n");
        }
    }
}
